#!/usr/bin/python3
import threading
import socket
import time
import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((400, 600))
pygame.display.set_caption("Tank demo")
pygame.key.stop_text_input()

font = pygame.font.SysFont("SimSun", 14)  # 1"Arial"
# text = None
# text_rect = None
menu = [None, None, None]  # ["命令状态","role列表","文本列表"]


# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 背景颜色
screen.fill((0, 0, 0))

# 绘制矩形
# pygame.draw.rect(screen, GREEN, [0, 5, 5, 5])

# player1 = pygame.transform.scale(pygame.image.load("./tank1.png"), (60, 60))
# player1 = pygame.transform.rotate(player1, 90)
# player1_position = [180, 0]
# player1_rotate = 180

player2 = pygame.transform.scale(pygame.image.load("./tank2.png"), (60, 60))
player2 = pygame.transform.rotate(player2, -90)
player2_position = [180, 520]
player2_rotate = 0

speed = 1 * 0.1


def messageShow(textlist=[]):
    """显示文本"""
    text_surfaces = [font.render(line, True, (0, 255, 0)) for line in textlist]
    text_positions = [
        (5, 400 + i * (text_surfaces[0].get_height() + 5))
        for i, _ in enumerate(textlist)
    ]
    for surface, pos in zip(text_surfaces, text_positions):
        screen.blit(surface, pos)


class mainThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.host = "192.168.31.211"
        self.port = 8010
        self.web = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.guid = ""
        self.isRun = True

    def stop(self):
        self.isRun = False
        self.web.close()

    def do_Send(self, text):
        text["guid"] = self.guid
        if self.isRun:
            self.web.send(f"{text}".encode("utf-8"))

    def alert_mes(self):
        print("上报线程")
        while self.isRun:
            time.sleep(2)
            if menu[0] == "fight":  # 发送位置和朝向
                data = {
                    "act": "gens",
                    "move": {
                        "ix": player2_position[0],
                        "iy": player2_position[1],
                        "iz": player2_rotate,
                        "speed": 0,
                    },
                    "look": {"iz": player2_rotate, "speed": 0},
                    "health": {"hp": "100/100", "mp": "100/100"},
                    "status": "fight",
                }
                self.do_Send(data)

    def run(self):
        print("开始线程：")
        buff = 512
        self.web.connect((self.host, self.port))
        threading.Thread(target=self.alert_mes).start()
        while True:
            time.sleep(0.1)
            try:
                s = self.web.recv(buff)
                if not s:
                    break
                # print(s.decode("utf-8"))
                self.msgManager(s.decode("utf-8"))
            except BaseException as err:
                print("ERR:", err)
                break
            # finally:
            #     self.web.send("\n\n".encode("utf-8"))
        print("开始结束：")

    def msgManager(self, msg):
        """消息接收管理器"""
        try:
            data = eval(msg)
        except BaseException as err:
            print(f"解码消息失败, 游戏终止. {err}")
            self.stop()
        # --------------------- 初始化消息 ------------------------- #
        if data.get("act") == "init":
            self.guid = data.get("guid")
            menu[2] = [
                data.get("msg"),
                "1  准备就绪",
            ]
            menu[0] = "wait"
        # --------------------- 接收数据 --------------------------- #
        guid = data.get("guid")
        if not guid == self.guid:
            self.newsManager(data)
            # print(f'Recv->{data.get("uid")}->{data.get("guid")}->{data}')
            return
        # --------------------- 玩家登录 --------------------------- #
        if data.get("act") == "login":
            if data.get("msg") == "登录成功":
                db = {"act": "role"}
                self.do_Send(db)
                menu[2] = None
        elif data.get("act") == "role":
            msg = ["选择您的载具:"]
            menu[1], x = data.get("data"), 0
            for i in menu[1]:
                msg.append(f"{x} {i[1]}-{i[2]}")
                x += 1
            menu[2] = msg
            menu[0] = "role"
        elif data.get("act") == "wait":
            menu[2] = ["等待战斗开始:", "1 准备就绪"]
            menu[0] = "wait"
        elif data.get("act") == "ready":
            menu[2] = ["等待战斗开始:", "1 取消准备"]
            menu[0] = "ready"
        else:
            pass

    def newsManager(self, data):
        """公共消息管理器"""
        print("公共消息:", data)
        if data.get("act") == "lock":
            menu[2] = [f'开始倒计时: {data.get("data")}']
            menu[0] = "lock"
        elif data.get("act") == "fight":
            menu[2] = None
            menu[0] = "fight"
        elif data.get("act") == "gens":
            pass
        else:
            pass


if __name__ == "__main__":
    print("Hello")
    isRun = True
    thread1 = mainThread()
    thread1.start()
    while isRun:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                isRun = False
            elif event.type == pygame.KEYUP:  # pygame.KEYDOWN
                # print("menu:", menu[0])
                if event.key == pygame.K_m:
                    messageShow(
                        ["1    登录用户#1", "2    登录用户#2", "3    登录用户#3\n"]
                    )
                    menu[0] = "login"
                if event.key == pygame.K_1 and menu[0] == "login":
                    data = {
                        "act": "login",
                        "data": {"username": "tttbbb999", "password": "123456"},
                    }
                    thread1.do_Send(data)
                    menu[0] = None
                if event.key == pygame.K_2 and menu[0] == "login":
                    data = {
                        "act": "login",
                        "data": {"username": "tttbbb888", "password": "123456"},
                    }
                    thread1.do_Send(data)
                    menu[0] = None
                if event.key == pygame.K_3 and menu[0] == "login":
                    data = {
                        "act": "login",
                        "data": {"username": "tttbbb777", "password": "123456"},
                    }
                    thread1.do_Send(data)
                    menu[0] = None

                if (
                    menu[0] == "role"
                    and event.key >= pygame.K_0
                    and event.key <= pygame.K_9
                ):
                    idx = event.key - pygame.K_0
                    data = {"act": "fight", "data": {"id": menu[1][idx][0]}}
                    thread1.do_Send(data)
                    menu[0] = None

                if event.key == pygame.K_1 and menu[0] == "wait":
                    data = {"act": "ready"}
                    thread1.do_Send(data)
                    menu[0] = None
                if event.key == pygame.K_1 and menu[0] == "ready":
                    data = {"act": "wait"}
                    thread1.do_Send(data)
                    menu[0] = None

        # 按住按键
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            if not player2_rotate == 0:
                player2 = pygame.transform.rotate(player2, -90)
                player2_rotate += 90
                if player2_rotate >= 360:
                    player2_rotate = 0
            player2_position[1] -= speed
            if player2_position[1] < 0:
                player2_position[1] = 0
        if keys[pygame.K_s]:
            if not player2_rotate == 180:
                player2 = pygame.transform.rotate(player2, -90)
                player2_rotate += 90
                if player2_rotate >= 360:
                    player2_rotate = 0
            player2_position[1] += speed
            if player2_position[1] > 540:
                player2_position[1] = 540
        if keys[pygame.K_a]:
            if not player2_rotate == 270:
                player2 = pygame.transform.rotate(player2, -90)
                player2_rotate += 90
                if player2_rotate >= 360:
                    player2_rotate = 0
            player2_position[0] -= speed
            if player2_position[0] < 0:
                player2_position[0] = 0
        if keys[pygame.K_d]:
            if not player2_rotate == 90:
                player2 = pygame.transform.rotate(player2, -90)
                player2_rotate += 90
                if player2_rotate >= 360:
                    player2_rotate = 0
            player2_position[0] += speed
            if player2_position[0] > 340:
                player2_position[0] = 340

        # 绘制背景
        screen.fill((0, 0, 0))

        # 绘制文本
        if menu[2]:
            messageShow(menu[2])

        # 显示player
        # screen.blit(player1, player1_position)
        screen.blit(player2, player2_position)
        # 更新屏幕
        # pygame.display.flip()
        # 绘制屏幕
        pygame.display.update()

    pygame.quit()
    thread1.stop()
    thread1.join()
    print("...Bye...")
